package com.zenithmind.news.websocket.handler;

import com.zenithmind.news.websocket.WebSocketMessageHandler;
import com.zenithmind.news.websocket.WebSocketSessionManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

/**
 * 心跳消息处理器 - 遵循单一职责原则
 * 专门处理心跳相关的WebSocket消息
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class HeartbeatMessageHandler implements WebSocketMessageHandler {

    private final WebSocketSessionManager sessionManager;

    @Override
    public String getSupportedMessageType() {
        return "HEARTBEAT";
    }

    @Override
    public WebSocketResponse handleMessage(WebSocketSession session, WebSocketRequest request, 
                                         WebSocketSessionManager.UserSessionInfo sessionInfo) {
        try {
            // 更新心跳时间
            sessionManager.updateHeartbeat(session.getId());
            
            log.debug("处理心跳消息：用户ID={}, 会话ID={}", sessionInfo.getUserId(), session.getId());
            
            return WebSocketResponse.system("HEARTBEAT_RESPONSE", "pong");
        } catch (Exception e) {
            log.error("处理心跳消息异常", e);
            return WebSocketResponse.error("HEARTBEAT_ERROR", "心跳处理失败");
        }
    }
}
